var interval, testModel;
var lockItem, itemName;
//存储
var storage = storages.create("dy_live_qg.js");

//时间工具类
// var timeUtils = require('TimeUtils.js');
var window = floaty.window(
    <frame>
        <vertical w="auto" h="auto" background='#66000000' gravity="center">
            <text id="title" text="抖音直播助手" gravity="top|center" textColor="red" textSize="13sp" margin="0 5" />
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal >
                <checkbox id="lockItem" text="指定商品:" textColor="white" />
                <input id="itemName" text="" hint="袋鼠医用" focusable="true" textColor="red" textSize="14sp" />
            </horizontal>
            <horizontal >
                <checkbox id="testModel" text="测试" textColor="white" />
            </horizontal>
            <horizontal >
                <text text="  提交频率(毫秒)：" gravity="top|left" textColor="white" />
                <input id="interval" text="100" hint="无" focusable="true" textColor="black" textSize="14sp" />
            </horizontal>
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal gravity="top|center">
                <button id="runButton" style="Widget.AppCompat.Button.Colored" text="开始" w="auto" h="*" />
                <button id="stopUi" style="Widget.AppCompat.Button.Colored" text="退出" w="auto" h="*" />
            </horizontal>
        </vertical>
    </frame>
);


window.setPosition(device.width / 2 - 400, device.width / 2 - 400);
window.exitOnClose();

window.title.on("click", () => {
    //开启位置调整
    window.setAdjustEnabled(!window.isAdjustEnabled());
});

window.itemName.on("touch_down", () => {
    window.requestFocus();
    window.itemName.requestFocus();
});

window.interval.on("touch_down", () => {
    window.requestFocus();
    window.interval.requestFocus();
});

//检查价格设置
window.lockItem.on("check", function (checked) {
    // 用户勾选价格校验
    if (checked) {
        // exectuion = engines.execScriptFile("time.js");
        if (!window.itemName.text()) {
            window.lockItem.checked = false;
            logError("指定商品名称必须填写！！！");
        }
    }
});

//退出
window.stopUi.on("click", () => {
    console.hide();
    window.close();
    floaty.closeAll();
    threads.shutDownAll();
    exit();
});


//*******************************************************************基础方法***************************************************************************************** */
//打开浮窗
function openConsole() {
    auto.waitFor()
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}

function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var ms = time.getMilliseconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s) + ":" + add00(ms);
}

// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    return now;
}

//*******************************************************************日志处理***************************************************************************************** */
// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}

//*******************************************************************日志处理***************************************************************************************** */
//*******************************************************************初始化设置***************************************************************************************** */
function initConfig() {
    ui.run(function () {
        //商品名称
        window.itemName.setText(storage.get("itemName", "").toString());

        window.lockItem.checked = storage.get("lockItem", false);

        //校验价格
        window.testModel.checked = false;

        //提交频率
        window.interval.setText(storage.get("interval", "100").toString());
    });

}
//*******************************************************************初始化设置***************************************************************************************** */
//*******************************************************************主程序***************************************************************************************** */

//*******************************************************************主程序***************************************************************************************** */

//开始
window.runButton.on("click", () => {

    window.disableFocus();
    //准备参数
    lockItem = window.lockItem.checked;
    //商品名称
    itemName = window.itemName.text();
    //校验价格
    testModel = window.testModel.checked;

    //提交订单频率 毫秒
    interval = parseInt(window.interval.getText());

    storage.put("lockItem", lockItem);

    storage.put("itemName", itemName);
    storage.put("interval", interval);

    //启动任务
    if (window.runButton.text() == "开始") {
        //保持屏幕常亮
        device.keepScreenOn();
        //开始任务
        threads.start(doJob);
        window.runButton.text("停止");
    } else {
        window.runButton.text("开始");
        logInfo("停止运行...");
        threads.start(function () {
            //关闭控制台
            // console.hide();
            device.cancelKeepingAwake();
            threads.shutDownAll();
        });
    }
});

//初始化数据
setTimeout(initConfig, 500);

//开启控制台
threads.start(openConsole);

logCommon("抖音直播检测模式");
logCommon("请进入直播页面...");

if (!textContains("说点什么").exists()) {
    logCommon("未进入直播间，请前往");
}

var checkThread = threads.start(function () {
    //在新线程执行的代码
    // logCommon( "购物车导航");
    while (true) {
        if (!textContains("说点什么").exists()) {
            logCommon("未进入直播间，请前往");
            textContains("说点什么").findOne();
            logCommon("已进入直播间，脚本将自动检测下单...");
        }
        sleep(1000);
    }
});

setInterval(() => { }, 1000);

//*******************************************************************主程序***************************************************************************************** */


/**
* 开始任务
*/
function doJob() {
    logInfo("开始运行...");

    var buyThread = threads.start(function () {
        //在新线程执行的代码
        let buyNow;
        while (true) {
            // waitForActivity("");
            buyNow = textContains("立即购买").findOne();
            if (buyNow.clickable()) {
                logCommon("立即购买-a：" + buyNow.click());
            } else {
                logCommon("立即购买-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
            }
            sleep(interval);
        }
    });

    var buyThread2 = threads.start(function () {
        //在新线程执行的代码
        let buyNow;
        while (true) {
            if (!textContains("说点什么").exists()) {
                buyNow = textContains("去购买").findOne();
                if (buyNow.clickable()) {
                    logCommon("去购买-a：" + buyNow.click());
                } else {
                    logCommon("去购买-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
            }
            sleep(interval);
        }
    });
    var buyThread3 = threads.start(function () {
        //在新线程执行的代码
        let buyNow;
        while (true) {
            if (!textContains("说点什么").exists()) {
                buyNow = textContains("去看看").findOne();
                if (buyNow.clickable()) {
                    logCommon("去看看-a：" + buyNow.click());
                } else {
                    logCommon("去看看-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
            }
            sleep(interval);
        }
    });


    var sku = threads.start(function () {
        let checkSku = true;
        let confirm;
        let pa;
        let groups;
        while (true) {
            confirm = textContains("确定").findOne();
            pa = confirm.parent().findOne(className("android.view.ViewGroup"));
            checkSku = true;
            if (pa) {
                //找出动态列表
                groups = className("android.view.ViewGroup").find();
                //遍历动态
                groups.forEach(function (group) {
                    let groupChild = group.children();
                    if (groupChild) {
                        let groupChildChild = groupChild.findOne(className("android.view.ViewGroup"));
                        if (groupChildChild) {
                            let groupChildChildText = groupChildChild.findOne(className("android.widget.TextView"));
                            if (groupChildChildText) {
                                // log(groupChildChildText.text());
                                if (groupChildChildText.text() == "确定") {
                                    let skuButton = groupChildChildText;
                                    if (skuButton.clickable()) {
                                        logInfo(groupChildChildText.text() + ":" + + skuButton.click());
                                    } else {
                                        logInfo(groupChildChildText.text() + ":" + click(skuButton.bounds().centerX(), skuButton.bounds().centerY()));
                                    }
                                } else if (groupChildChildText.text() != "查看详情") {
                                    if (checkSku) {
                                        let skuButton = groupChildChildText;
                                        if (skuButton.clickable()) {
                                            logInfo("选择:" + groupChildChildText.text() + ":" + skuButton.click());
                                        } else {
                                            logInfo("选择:" + groupChildChildText.text() + ":" + click(skuButton.bounds().centerX(), skuButton.bounds().centerY()));
                                        }
                                        checkSku = false;
                                    }
                                }
                            }
                        }
                    }
                });
            } else {
                className("android.widget.TextView").clickable(true).find().forEach(function (group) {
                    // log(group.text());
                    if (group.text() == "确定") {
                        if (group.clickable()) {
                            logInfo(group.text() + ":" + group.click());
                        } else {
                            let scope = group.bounds();
                            logInfo(group.text() + ":" + click(scope.centerX(), scope.centerY()));
                        }
                    } else {
                        if (checkSku) {
                            if (group.clickable()) {
                                logInfo("选择:" + group.text() + ":" + group.click());
                            } else {
                                let scope = group.bounds();
                                logInfo("选择:" + group.text() + ":" + click(scope.centerX(), scope.centerY()));
                            }
                            checkSku = false;
                        }
                    }
                });
            }
        }
    });

    var submitThread = threads.start(function () {
        let submit;
        let scope;
        while (true) {
            submit = text("提交订单").findOne();
            if (testModel) {
                logError("测试模式不提交");
            } else {
                if (submit.clickable()) {
                    logCommon("提交订单-a：" + submit.click());
                } else {
                    scope = submit.bounds();
                    logCommon("提交订单-as：" + click(scope.centerX(), scope.centerY()));
                }
                sleep(interval);
            }
        }
    });


    var successThread = threads.start(function () {
        //在新线程执行的代码
        let payButton;
        while (true) {
            payButton = textContains("立即付款").findOne();
            logError(timeUtils.getLogTime(), "下单成功");
            if (autoPay) {
                payButton.parent().click();
                logError(timeUtils.getLogTime(), "尝试支付...");
            }
            sleep(1000);
            threads.shutDownAll();
            return;
        }
    });

    var addCartThread = threads.start(function () {
        //在新线程执行的代码
        let buyNow;
        while (true) {
            if (textContains("说点什么").exists()) {
                buyNow = boundsInside(0, device.height / 2, device.width, device.height).className("android.widget.FrameLayout").clickable(true).depth(15).findOne()
                logInfo("有宝贝出现了...")
                if (!lockItem) {
                    if (buyNow.clickable()) {
                        logInfo("立即抢购-a：" + buyNow.click());
                    } else {
                        logInfo("立即抢购-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                    }
                } else if (lockItem && textContains(itemName).exists()) {
                    if (buyNow.clickable()) {
                        logInfo("立即抢购-a：" + buyNow.click());
                    } else {
                        logInfo("立即抢购-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                    }
                } else {
                    logError("不是目标商品...")
                }
            }
            sleep(interval);
        }
    });


    //保持脚本运行
    setInterval(() => { }, 1000);
}


//=======================================================sku=============================================================//
